import datetime
from django.core.files.storage import Storage
from django.conf import settings
from django.utils.deconstruct import deconstructible
from qiniu import Auth

import os,time

from qiniu import BucketManager
from qiniu import etag
from qiniu import put_data
from qiniu import put_file

@deconstructible
class QiNiuStorage(Storage):

    def __init__(self):
        # 需要填写你的 Access Key 和 Secret Key
        self.__access_key = settings.QINIU_ACCESS_KEY
        self.__secret_key = settings.QINIU_SECRET_KEY
        self.__base_url =settings.QINIU_BASE_URL
        self.__bucket_name = settings.QINIU_BUCKET_NAME
        # 构建鉴权对象
        self.qiniu_server = Auth(self.__access_key, self.__secret_key)

    def open(self, name, mode='rb'):
        pass

    def save(self, name, content, max_length=None):

        # 上传后保存的文件名
        key = self.__trans_name(name)
        # 生成上传 Token，可以指定过期时间等
        token = self.qiniu_server.upload_token( self.__bucket_name, key, 3600)
        # 要上传文件的本地路径
        localfile = content.file
        ret, info = put_data(token, key, localfile if isinstance(localfile,bytes) else localfile.read())
        if info.status_code == 200:
            print('上传返回路径'+ret['key'])
            return ret['key']

        else:
            raise Exception('上传失败')

    def exists(self, name):

        return False


    def delete(self, name):

        # 初始化BucketManager
        bucket = BucketManager(self.qiniu_server)
        # 你要测试的空间， 并且这个key在你空间中存在
        bucket_name = self.__bucket_name
        key = name
        # 删除bucket_name 中的文件 key
        ret, info = bucket.delete(bucket_name, key)
        if info.status_code==200:
            return True
        else:
            raise Exception('删除失败')

    def url(self, name):
        return os.path.join(self.__QINIU_BASE_URL,name)


    @staticmethod
    def __trans_name(name):
        file_extension = name.rsplit('.',1).pop()
        file_date = datetime.datetime.now().strftime('%Y-%m-%d')
        file_name= name.rsplit('.',1)[0] + str(int(time.time()))
        return 'image/bigevent/{}/{}.{}'.format(file_date,file_name,file_extension)

    # def __trans_name(name):
    #     # file_extension = name.rsplit('.',1).pop()
    #     file_date = datetime.datetime.now().strftime('%Y-%m-%d')
    #     # file_name= name.rsplit('.',1)[0] + int(time.time())
    #     file_name= name + str(int(time.time()))
    #
    #     # return 'image/bigevent/{}/{}.{}'.format(file_date,file_name,file_extension)
    #     return 'image/bigevent/{}/{}'.format(file_date,file_name)
